//
//  BQMarketViewController.m
//  BeeQuick
//
//  Created by mac on 16/11/18.
//  Copyright © 2016年 six_group. All rights reserved.
//

#import "BQMarketViewController.h"
#import "BQYLLeftTableViewCell.h"
#import "BQYLRightTableViewCell.h"
#import "DSHTTPClient.h"
#import "BQYLGoodsModel.h"
#import "BQYLDetailsModel.h"
#import <YYModel.h>
#import <UIImageView+WebCache.h>
#import <SVProgressHUD.h>
#import "BQYLDetailsViewController.h"
#import "BQSaoYiSaoViewController.h"


//首页的model
#import "BQHomeGoodModel.h"

#import "BQYLGoodsViewController.h"

static NSString *leftCell = @"leftCell";
static NSString *rightCell = @"rightCell";
//判断数据加载是否完成的旗帜变量
static int flag = 0;

@interface BQMarketViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
CAAnimationDelegate,
BQYLRightTableViewCellDelegate

>

@property(nonatomic,weak)UITableView *leftTableView;
@property(nonatomic,weak)UITableView *rightTableView;

//左边的table
@property(nonatomic,strong)NSArray <BQYLGoodsModel *> *goodsArray;
//右边
@property(nonatomic,strong)NSMutableArray <BQYLDetailsModel *> *modelList;

//右边 table 每一组的  模型数组保存
@property(nonatomic,strong)NSArray <NSArray< BQHomeGoodModel *>*> *goodsList;

@property(nonatomic,strong)NSDictionary *detailDic;


@end

@implementation BQMarketViewController
{
#warning 放这里没问题吗?? 这里默认强引用.....?
    UIView *_whiteView;
   //左侧的cell
    UITableViewCell *_cell;
}
#pragma mark - 懒加载
-(NSArray<BQYLGoodsModel *> *)goodsArray
{
    if (!_goodsArray)
    {
        _goodsArray = [NSArray array];
    }
    return _goodsArray;
    
}

-(NSArray<BQYLDetailsModel *> *)modelList
{
    if (!_modelList)
    {
        _modelList = [NSMutableArray array];
        
    }
    return _modelList;
}

-(NSDictionary *)detailDic
{
    if (!_detailDic)
    {
        _detailDic = [[NSDictionary alloc]init];
    }
    return _detailDic;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getData];
    
    [self setupUI];
    
    
    
    
}

#pragma mark - 右边加减View的代理方法

//加号方法
- (void)rightCell:(BQYLRightTableViewCell *)rightCell withAddModel:(BQYLDetailsModel *)model withStartPoint:(CGPoint)startP
{
    if (![self.modelList containsObject:model])
    {
        [self.modelList addObject:model];
    }
    
    [self creatAnimateStartPoint:startP WithModel:model];
    NSLog(@"%f,%f",startP.x,startP.y);
}


//减号方法
- (void)rightCell:(BQYLRightTableViewCell *)rightCell withMinusModel:(BQHomeGoodModel *)model
{
    //改下面购物车的 红点的数量
}

#pragma mark - 创建动画
- (void)creatAnimateStartPoint:(CGPoint)startPoint WithModel:(BQYLDetailsModel *)model
{
    UIImageView *picView = [[UIImageView alloc]init];
    
    NSURL *url = [NSURL URLWithString:model.img];
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    //添加图片的动画
    picView.bounds = CGRectMake(0, 0, 50, 50);
    
    [picView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        //把动画图片添加到window
        [keyWindow addSubview:picView];
        
        //关键帧动画
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        
        //起点
        [path moveToPoint:startPoint];
        
        //终点
        CGPoint endPoint = CGPointMake(kScreenW * 0.65, kScreenH - 46);
        
        //路径
        [path addLineToPoint:endPoint];
        
        anim.path = path.CGPath;
        
        //时间
        anim.duration = 0.6;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            picView.transform = CGAffineTransformMakeScale(0.2, 0.2);
            
        }];
        
        
        anim.delegate = self;
        
        [anim setValue:picView forKey:@"endImage"];
        
        [picView.layer addAnimation:anim forKey:@"keyAnim"];
        
        
        
        
    }];
    
    
    
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    UIImageView *endView = [anim valueForKey:@"endImage"];
    
    [endView removeFromSuperview];
    
    
}
#pragma mark - 设置组头标题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    /*
     以为UILabel继承UIView ,可以自定义组头, 设置标题
     这样可以设置字号
     */
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.backgroundColor = [UIColor cz_colorWithHex:0xefefef];
    titleLabel.font = [UIFont systemFontOfSize:14];
    
    titleLabel.text = self.goodsArray[section].name;
    return titleLabel;
}



#pragma mark - 利用组尾间距来优化界面
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
  //从购物车切过啦,这边刷新一下
    if(self.rightTableView)
    {
        [self.rightTableView reloadData];
    }
    
    UIView *whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    whiteView.backgroundColor = [UIColor whiteColor];
    
    //关联
    _whiteView = whiteView;
    
    if (!flag) {
        
        [self.view addSubview:whiteView];
        //MARK: 数据加载时候展示  正在加载 菊花
        [SVProgressHUD showWithStatus:@"正在加载"];
        //菊花框样式  自定义
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
        //菊花框背景颜色
        [SVProgressHUD setBackgroundColor:[UIColor cz_colorWithHex:0xF9F9F9]];
    }
}
#pragma mark - UI界面
- (void)setupUI
{

    
    
    //MARK: - 设置左侧扫一扫一右侧搜索.
        UIBarButtonItem *scanBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_black_scancode"] style:UIBarButtonItemStylePlain target:self action:@selector(scan:)];
    
    
        [self.navigationItem setLeftBarButtonItem:scanBarButton];
    
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_search"] style:UIBarButtonItemStylePlain target:self action:@selector(search:)];
    
        [self.navigationItem setRightBarButtonItem:rightBarButton];
    
    
    UIView * titleView = [[UIView alloc]init];
    UILabel  *titleLabel = [[UILabel alloc]init];
    
    titleLabel.text = @"配送";
    
    self.navigationItem.title;
    
    
    
    
    
//    self.navigationItem.titleView
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //MARK:1. 左边table
    //左侧的tableView 不设置frame 约束中设置
    UITableView *leftTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    //添加到view
    [self.view addSubview:leftTableView];
    
    //MARK:2. 右边table
    UITableView *rightTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    
#warning 这个是干嘛用的?
    UIImageView *footView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"v2_common_footer"]];
    footView.contentMode = UIViewContentModeCenter;
    rightTableView.tableFooterView = footView;
    
    
    //添加
    [self.view addSubview:rightTableView];
    
    //MARK:3. 数据源
    leftTableView.dataSource = self;
    rightTableView.dataSource = self;
    
    //MARK:4. 代理
    leftTableView.delegate = self;
    rightTableView.delegate = self;
    leftTableView.dataSource = self;
    rightTableView.dataSource = self;
    
    //MARK:5. 关联
    self.leftTableView = leftTableView;
    self.rightTableView = rightTableView;
    
    //MARK:6. 注册
    [leftTableView registerClass:[BQYLLeftTableViewCell class] forCellReuseIdentifier:leftCell];
    [rightTableView registerNib:[UINib nibWithNibName:@"BQYLRightTableViewCell" bundle:nil]forCellReuseIdentifier:rightCell];
    
    //MARK:7. 约束
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.view);
        make.width.mas_equalTo(86);
        make.bottom.equalTo(self.view);
    }];
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.right.equalTo(self.view);
        make.left.equalTo(leftTableView.mas_right);
        make.bottom.equalTo(self.view).offset(-49);
    }];
    
    //MARK:8. 行高
    leftTableView.rowHeight = 45;
//    rightTableView.estimatedRowHeight = 80;
    rightTableView.rowHeight = 80;
    rightTableView.sectionHeaderHeight = 25;
    
    //MARK:9. 取消下划线
    leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}

#pragma mark - 网络获取数据
-(void)getData
{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    
    [dataDic setValue:@"5" forKey:@"call"];
    
    [DSHTTPClient postUrlString:@"supermarket.json.php" withParam:dataDic withSuccessBlock:^(id data) {
        //从DATA中获取左边名字
        NSArray *array = data[@"data"][@"categories"];
        NSDictionary *dict = data[@"data"][@"products"];
        
        // 遍历数组 得到类型模型
        
        NSMutableArray *tempArr1 = [NSMutableArray array];
         NSMutableArray *tempArr2 = [NSMutableArray array];
        for (int i = 0; i < array.count; i++) {
            
            NSDictionary *category = array[i];
            
            // 字典转模型
            BQYLGoodsModel *cate = [BQYLGoodsModel yy_modelWithDictionary:category];
            [tempArr1 addObject:cate];
            
            
            // 获取当前模型对应的id
            NSArray *goodsTempArray = dict[ cate.shopID];
            
            // 遍历数组 进行商品的字典转模型
            
            NSArray *goodsArray = [NSArray yy_modelArrayWithClass:[BQHomeGoodModel class] json:goodsTempArray];
            
            [tempArr2 addObject:goodsArray];
        }
        
        self.goodsArray = tempArr1.copy;
        self.goodsList = tempArr2.copy;
        
#warning 关键的模型转换
//        NSArray *goodsArr = [NSArray yy_modelArrayWithClass:[BQYLGoodsModel class] json:array];
//        
//        self.goodsArray = goodsArr.copy;        
//        
//        self.detailDic = data[@"data"][@"products"];
//        
//        NSMutableArray *arrM = [NSMutableArray array];
        
        
//        [self.goodsArray enumerateObjectsUsingBlock:^(BQYLGoodsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            
//            NSArray * tempArr = [NSArray yy_modelArrayWithClass:[BQHomeGoodModel class] json:self.detailDic[obj.shopID]];
//            
//            [arrM addObject:tempArr];
//        }];
//        
//        self.goodsList = arrM.copy;
//        
//        NSLog(@"%@",[NSThread currentThread]);// 这里已经是主线程了
        
        //主队列刷UI

////MARK: - 数据加载完成关闭加载菊花.
            [SVProgressHUD dismiss];
        //让那个白色的那背景消失
        [_whiteView removeFromSuperview];

            flag = 1;
            [self.leftTableView reloadData];
            [self.rightTableView reloadData];
//
        
    } withFailedBlock:^(NSError *error) {
        
    } withErrorBlock:^(NSString *message) {
        
    }];
}

//离开此控制器让菊花消失
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [SVProgressHUD dismiss];
//}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated]; // 这句话还是要加的把....
    [_whiteView removeFromSuperview];
    [SVProgressHUD dismiss];
}




//点左侧cell 动右侧  点右cell 到新页
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    //左边cell
//    if (tableView == self.leftTableView)
//    {
//        
//        if (indexPath.row != 0)
//        {
//            UITableViewCell *cell = [self.leftTableView cellForRowAtIndexPath:indexPath];
//            
//            _headView.headLabel.text = cell.textLabel.text;
//
//            _cell.selected = NO;
//        }
//        NSString *shopID = self.goodsArray[indexPath.row].shopID;
//        NSArray *array = self.detailDic[shopID];
//        NSMutableArray *modelList = [[NSMutableArray alloc]init];
//        
//        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            
//            BQYLDetailsModel *model = [[BQYLDetailsModel alloc]init];
//            
//            [model setValuesForKeysWithDictionary:obj];
//            
//            [modelList addObject:model];
//        }];
//        
//        self.modelList = modelList.copy;
//        
//        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
//            [self.rigthTableView reloadData];
//            
//            
//            
//            [_whiteView removeFromSuperview];
//            
//            
//        }];
//    }
//    //右侧cell
//    else if (tableView == self.rigthTableView)
//    {
//        BQYLPageController *pageVC = [[BQYLPageController alloc]init];
//        
//        //传递数据 所有数据
//        pageVC.goodsArray = self.goodsArray;
//        
//        //传递选中角标
//        pageVC.selectIndexPath = indexPath;
//        
//        //传递已经选择的数据
//        pageVC.selectArray = self.modelList;
//        
//        
//        [self.navigationController pushViewController:pageVC animated:YES];
//        
//        
//    }
//    
//    
//    
//    
//}




#pragma mark - 数据源方法
//行
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if(tableView == _leftTableView)
    {
        return 1;
    }
    
    return _goodsArray.count;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _rightTableView)
    {
        //如果是右边的table

        return self.goodsList[section].count;
    }

    //左边的table
    return _goodsArray.count;
    
    
}

//cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //定义CELL
    UITableViewCell *cell;
    if (tableView == _leftTableView)//左侧的table
    {

        cell = [tableView dequeueReusableCellWithIdentifier:leftCell forIndexPath:indexPath];
        cell.textLabel.text = _goodsArray[indexPath.row].name;
        
    }
    else if(tableView == _rightTableView)//右侧的table
    {
        
       cell = [tableView dequeueReusableCellWithIdentifier:rightCell forIndexPath:indexPath];
        
        ((BQYLRightTableViewCell *)cell).model = self.goodsList[indexPath.section][indexPath.row];
        
//        BQYLDetailsModel *model = _modelList[indexPath.row];
        
//        BQYLGoodsModel *Marketmodel = _goodsArray[indexPath.section];
        
//        __block NSInteger modeIndex;
#warning 求逻辑优化
//        [_goodsList enumerateObjectsUsingBlock:^(NSArray<BQHomeGoodModel *> * _Nonnull array, NSUInteger idxOne, BOOL * _Nonnull stop) {
//            
//            [array enumerateObjectsUsingBlock:^(BQHomeGoodModel * _Nonnull obj, NSUInteger idxTwo, BOOL * _Nonnull stop) {
//                
//                NSString *pid = [NSString stringWithFormat:@"a%@",obj.cid];
//              
//#warning 到时候新数据就不用拼接
//                
//                if([pid isEqualToString:Marketmodel.shopID])
//                {
//                    modeIndex = idxOne;
//                }
//                
//            }];
//            
//            
//        }];
        //取出要赋值的模型
//        BQHomeGoodModel *goodsModel = _goodsList[modeIndex][indexPath.row];
//        ((BQYLRightTableViewCell *)cell).model = model;
        
//        ((BQYLRightTableViewCell *)cell).model = goodsModel;
        
        ((BQYLRightTableViewCell *)cell).delegate = self;
        
    }
    
    return cell;
}





//点左侧cell 动右侧  点右cell 到新页

#pragma mark - cell的点击事件 didSelect方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //左边cell
    if (tableView == self.leftTableView)
    {
        //点击实现右侧滚动
        //右边tableView将要滚动的 下标
        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        
        [_rightTableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        //记得return
      return;
    }else{//右侧cell
        
        BQYLGoodsViewController *vc = [[BQYLGoodsViewController alloc]init];
#warning 特别提示  注意顺序
        // 数据传递
        vc.currentIndexPath = indexPath;
        vc.goodsList = self.goodsList;
        vc.view.backgroundColor = [UIColor yellowColor];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (tableView == self.leftTableView)
    {

//        [self tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        return;
        
    };
    //判断是否是自动滚动

    //如果是自动滚动的
    if(!(_rightTableView.tracking ||_rightTableView.decelerating || _rightTableView.dragging))
    {
        return;
    }


//    MARK: - 滑动右边的时候,联动左边.
        //构造一个角标给左侧
        NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:indexPath.section inSection:0];

        //让左侧自动选中

        [self.leftTableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
}



#pragma mark  扫一扫及搜索
//MARK: - 扫一扫.
- (void)scan:(UIBarButtonItem*)btn
{
    // 跳转控制器
    BQSaoYiSaoViewController *vc = [[BQSaoYiSaoViewController alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
}

//MARK: - 搜一搜.
- (void)search:(UIBarButtonItem *)btn
{
    NSLog(@"我是搜一搜");
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
/*
 #pragma mark - 设置组间距
 //section头部间距
 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
 {
 return 1;//section头部高度
 }
 //section头部视图
 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
 {
 UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 1)];
 view.backgroundColor = [UIColor clearColor];
 return view;
 }
 //section底部间距
 - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
 {
 return 1;
 }
 //section底部视图
 - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
 {
 UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 1)];
 view.backgroundColor = [UIColor clearColor];
 return view;
 }
 
 */
@end
